/**
 * admui-basic v2.1.0 (http://www.admui.com/)
 * Copyright 2015-2019 Admui Team
 * Licensed under the Admui License 1.1 (http://www.admui.com/about/license)
 */
(function(document, window, $) {
  'use strict';

  /* global autosize, toastr */

  window.App.extend({
    scrollChatsToBottom: function() {
      // 保持消息界面在底部
      var $chatsWrap = $('.page-message-chats');

      $chatsWrap.scrollTop(
        $('.chats', $chatsWrap).outerHeight() + $('#historyBtn').outerHeight() - $chatsWrap.height()
      );
    },
    handleResize: function() {
      // 屏幕尺寸变化时滚动条到底部
      var self = this;

      $(window).on('resize', function() {
        self.scrollChatsToBottom();
      });
    },
    handleTalking: function() {
      var self = this;
      var $chatsWrap = $('.page-message-chats');
      var $textareaWrap = $('.page-message-input');

      // 为消息输入框初始化响应式插件
      autosize($('.message-input textarea'));

      // 消息输入框尺寸变化时
      $(document).on('autosize:resized', '.message-input textarea', function() {
        var height = $textareaWrap.outerHeight();

        $chatsWrap.css('height', 'calc(100% - ' + height + 'px)');
        self.scrollChatsToBottom();
      });

      // 发送消息
      $(document).on('click', 'button.message-input-btn', function() {
        var $messageInput = $('.message-input>.form-control');
        var talkContents = $.trim($messageInput.val());
        var $newMsg = $('<div class="chat-content"><p>' + talkContents + '</p></div>');

        if (talkContents !== '') {
          $('.chat')
            .last()
            .find('.chat-body')
            .append($newMsg);
          $messageInput.val('');
        } else {
          toastr.warning('不能发送空白消息');
        }

        $messageInput.focus();

        self.scrollChatsToBottom();
      });
    },
    run: function() {
      this.scrollChatsToBottom();
      this.handleResize();
      this.handleTalking();
    }
  });

  $(function() {
    window.App.run();
  });
})(document, window, jQuery);
